<template>
  <el-drawer :modelValue="modelValue" :with-header="false" direction="btt" :show-close="false" :close-on-press-escape="false" class="my-drawer">
    <div class="home-board-screen" id="screen">
      <div class="home-board-header">
        <div class="left">
          <div class="flex-1">
            <!-- <el-select v-model="platformValue" clearable class="w-[160px]">
              <el-option label="全部平台" value="" />
              <el-option v-for="item in platformOpt" :key="item.platform_id" :label="item.platform_name" :value="item.platform_id" />
              <template #prefix>
                <el-icon class="text-[#3487ff]"><Search /></el-icon>
              </template>
            </el-select> -->
          </div>
          <!-- @click="toggleFullScreen" -->
          <!-- <div>天气</div> -->
        </div>
        <div class="title" :style="{ backgroundImage: `url(${titleUrl})` }">
          <!-- 信诚节日大屏 -->
        </div>
        <div class="right">
          <div class="flex-1" style="letter-spacing: 0.6px">
            北京时间 {{ timeData.time }} <span class="border-divider">{{ timeData.date }}</span> {{ timeData.week }}
          </div>
          <div @click="handleClose" class="cursor-pointer">
            <div class="flex items-center close-Btn">
              <el-icon><SwitchButton /></el-icon> 退出
            </div>
          </div>
        </div>
      </div>

      <div class="home-board-panel flex items-center" id="panel-view">
        <Snackbar :height="panelViewHeight" :modelValue="modelValue" />
        <span class="panel-box">
          <div class="panel-item panel-item-income">
            <div class="panel-title">销售额USD</div>
            <!-- {{ festival_order_stat.income }} -->
            <div class="num-box">
              <template v-for="(v, i) in festival_order_stat.income" :key="i">
                <NumRoll :number="v"></NumRoll>
              </template>
            </div>
          </div>
          <div class="panel-item">
            <div class="panel-title">订单量</div>
            <!-- {{ festival_order_stat.count }} -->
            <div class="num-box">
              <template v-for="(v, i) in festival_order_stat.count" :key="i">
                <NumRoll :number="v"></NumRoll>
              </template>
            </div>
          </div>
          <div class="panel-item">
            <div class="panel-title">客单价USD</div>
            <!-- {{ festival_order_stat.avg_order_price }} -->
            <div class="num-box">
              <template v-for="(v, i) in festival_order_stat.avg_order_price" :key="i">
                <NumRoll :number="v"></NumRoll>
              </template>
            </div>
          </div>
        </span>
        <div class="code">
          <img src="https://xc-erp-login.oss-cn-shenzhen.aliyuncs.com/login/IM.png" alt="" />
          <!-- <div class="text">扫一扫</div> -->
        </div>

        <div class="Barrage"></div>
      </div>

      <div class="home-board-body" v-if="modelValue">
        <div class="left">
          <div class="body-title flex items-center">
            <span class="icona flex items-center justify-center">
              <span class="iconb"></span>
            </span>
            <span class="cn-label"> 热门类目<span class="text-[#999]"> /</span></span>
            <span class="en-label"> Popular categories </span>
          </div>
          <div class="body-list">
            <div v-for="(item, i) in festival_sales_ranking.category_ranking" :key="i" class="body-list-item flex items-center">
              <span class="serial">
                {{ i + 1 }}
              </span>
              <div class="progress">
                <div class="title">{{ item.name || "-" }}</div>
                <div class="flex">
                  <el-progress :percentage="item.percentage" :show-text="false" class="w-[276px]"> </el-progress>

                  <div class="order-num font-bold">{{ item.amount }} <span class="text-[12px]">USD</span></div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <CountryChart class="view" />

        <div class="right">
          <div class="body-title flex items-center">
            <span class="icona flex items-center justify-center">
              <span class="iconb"></span>
            </span>
            <span class="cn-label"> 今日成交榜单 <span class="text-[#999]"> /</span></span>
            <span class="en-label"> Today's Transaction list </span>
          </div>
          <div class="ranking">
            <div class="ranking-header ranking-row">
              <span v-for="i in rankingColumn" :key="i.value" :class="`inline-block ${i.class}`">{{ i.label }}</span>
            </div>

            <div v-for="(row, index) in festival_sales_ranking.department_ranking[rankingAtv]" :key="row.value" class="ranking-body ranking-row flex items-center">
              <span v-for="i in rankingColumn" :key="i.value" :class="`inline-block ranking-row flex items-center ${i.class}`">
                <!-- 排名 -->
                <div v-if="i.value == 'ranking'" class="ranking-idx">
                  <img src="@/assets/images/top_1.png" v-if="index == 0" class="ranking-icon" />
                  <img src="@/assets/images/top_2.png" v-else-if="index == 1" class="ranking-icon" />
                  <img src="@/assets/images/top_3.png" v-else-if="index == 2" class="ranking-icon" />
                  <span v-else>
                    {{ index + 1 }}
                  </span>
                </div>
                <!-- 部门 -->
                <el-text class="name" truncated v-else-if="i.value == 'name'" line-clamp="2">
                  {{ row?.[i.value] }}
                </el-text>

                <el-text class="w-[100%]" style="font-family: Futura, Futura" truncated v-else>
                  {{ row?.[i.value] }}
                </el-text>
              </span>
            </div>

            <!-- <div class="ranking-btn">
              <div class="top" :class="rankingAtv == 'first_depart_ranking' ? 'atv' : 'atv2'" @click="rankingAtv = 'first_depart_ranking'">
                <div class="btn">一级部门</div>
              </div>
              <div class="bottom" :class="rankingAtv == 'second_depart_ranking' ? 'atv' : ''" @click="rankingAtv = 'second_depart_ranking'">
                <div class="btn">末级部门</div>
              </div>
            </div>
          </div> -->
          </div>
          <div class="ranking-btn">
            <div class="top" :class="rankingAtv == 'first_depart_ranking' ? 'atv' : 'atv2'" @click="rankingAtv = 'first_depart_ranking'">
              <div class="btn">一级部门</div>
            </div>
            <div class="bottom" :class="rankingAtv == 'second_depart_ranking' ? 'atv' : ''" @click="rankingAtv = 'second_depart_ranking'">
              <div class="btn">末级部门</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </el-drawer>
</template>

<script setup>
import { nextTick } from "vue"

import { configSettingDetail } from "./api"

// 弹幕
import Snackbar from "./components/Snackbar.vue"
import NumRoll from "./components/NumRoll.vue"

import CountryChart from "./components/CountryChart/index.vue"
import socketStore from "@/store/modules/socket"
const useWebSocketStore = socketStore()
const props = defineProps({
  modelValue: { type: Boolean, default: false },
})
const emit = defineEmits(["update:modelValue"])

// 关闭全屏
const isFullScreen = ref(false)
const toggleFullScreen = () => {
  if (document?.fullscreenElement) {
    document.exitFullscreen()
  }
}
const handleClose = () => {
  toggleFullScreen()
  emit("update:modelValue", false)
}
const titleUrl = ref("")
// import { initSocket } from "@/utils/socket"
let aws = ref(null)
onMounted(async () => {})
watch(
  () => props.modelValue,
  (v) => {
    if (v) {
      configSettingDetail({ key: "is_festival" }).then((res) => {
        if (res?.data?.value == 0) {
          titleUrl.value = "https://xc-goods.oss-cn-shenzhen.aliyuncs.com/20240808/data/Company/%28text%20%402x%29%2B02375231251b562debedd21285b7b97963b15ad8d.png"
        } else {
          titleUrl.value = "https://xc-goods.oss-cn-shenzhen.aliyuncs.com/20240808/data/Company/%28text%20%402x77%29%2B023730377a8814793854aae4bf5d98c0262090e12.png"
        }
      })
      // aws.value = initSocket()
      setTimeout(() => {
          useWebSocketStore.sendMessage({event: "subscribe",param: ["festival_sales_ranking","festival_order_stat","festival_site_country_stat"]});
          useWebSocketStore.sendMessage({event: "festival_sales_ranking"});
          useWebSocketStore.sendMessage({event: "festival_order_stat"});
          useWebSocketStore.sendMessage({event: "festival_site_country_stat"});
      }, 500)

      // 假数据
      // initFestivalStat()
      // 刷新时间
      getDate()
      // 监听窗口大小变化事件
      window.addEventListener("resize", scaleView)
      setTimeout(() => {
        //  弹幕 视图高度
        getPanelViewHeight()
      }, 2000)
    } else {
      // 监听窗口大小变化事件
      window.removeEventListener("resize", scaleView)
      // aws.value.close("1000", "服务端结束连接")
      useWebSocketStore.sendMessage({ event: "cancel_subscribe", param: ["festival_sales_ranking", "festival_order_stat", "festival_site_country_stat"] })
    }
  }
)

// import socketStore from "@/store/modules/socket"
const festival_order_stat = computed(() => {
  // income: 销售额     count: 订单量     avg_order_price: 客单价
  let data = socketStore().festival_order_stat
  // console.log("festival_order_stat")
  // console.log(data)
  data.income = padZero(data.income, 10).split("")
  data.count = padZero(data.count, 7).split("")
  data.avg_order_price = padZero(data.avg_order_price, 7).split("")
  return data
})

const padZero = (num, length) => {
  return String(num).padStart(length, "0")
}
// 假数据
// const initFestivalStat = () => {
//   setTimeout(() => {
//     socketStore().festival_order_stat = {
//       income: getRandomNumber(10000, 99999999).toFixed(1),
//       count: Math.round(Math.random() * (9876543 - 1000) + 1000),
//       avg_order_price: Number(Math.round(Math.random() * (9876 - 1) + 1)).toFixed(2),
//     }
//     if (props.modelValue) initFestivalStat()
//   }, 5000)
// }
// const getRandomNumber = (min, max) => {
//   return Math.floor(Math.random() * (max - min + 1)) + min
// }

// 销售平台
const platformValue = ref("")
const platformOpt = computed(() => {
  return socketStore().festival_sales_ranking.platform_ranking
})

// 今日成交榜单 维度
const rankingAtv = ref("second_depart_ranking")
// 今日成交榜单 列表
const rankingColumn = [
  { label: "排名", value: "ranking", class: "w-[50px]" },
  { label: "部门", value: "name", class: "w-[130px]" },
  { label: "销售额USD", value: "amount", class: "w-[116px]" },
  { label: "订单量", value: "order_qty", class: "w-[80px]" },
]

// 热门类目  今日成交榜单
const festival_sales_ranking = computed(() => {
  let data = socketStore().festival_sales_ranking
  // console.log("festival_sales_ranking")
  // console.log(data)
  if (platformValue.value) {
    data = data.platform_ranking.find((v) => v.platform_id == platformValue.value)?.ranking
  } else {
    data = data.total_ranking
  }

  let categoryMax = Math.max(...data.category_ranking.map((v) => Number(v.amount), 0))
  data.category_ranking.forEach((item) => {
    item.percentage = (Number(item.amount) / categoryMax).toFixed(2) * 100
  })
  // console.log("festival_sales_ranking")
  // console.log(data)
  return data
})

const scaleView = () => {
  // 初始化自适应-在刚显示的时候就开始适配一次
  handleScreenAuto()
  // 绑定自适应函数-防止浏览器栏变化后不再适配（这里可做节流优化）
  window.onresize = () => handleScreenAuto()
}
// 数据大屏自适应函数
const handleScreenAuto = () => {
  const designDraftWidth = 1920 // 设计稿的宽度
  const designDraftHeight = 1080 // 设计稿的高度
  // 根据屏幕的变化适配的比例
  const scale =
    document.documentElement.clientWidth / document.documentElement.clientHeight < designDraftWidth / designDraftHeight
      ? document.documentElement.clientWidth / designDraftWidth
      : document.documentElement.clientHeight / designDraftHeight
  // 缩放比例
  document.querySelector("#screen").style.transform = `scale(${scale}) translate(-100%)`
}

// 弹幕 视图高度
const panelViewHeight = ref(0)
const getPanelViewHeight = () => {
  panelViewHeight.value = document.getElementById("panel-view").offsetHeight - 40
}
// 时间
const timeData = ref({
  date: "2024/01/01",
  time: "12:00:00",
  week: "星期 ",
})
import { parseTime } from "@/utils/ruoyi"
const getDate = () => {
  setTimeout(() => {
    timeData.value.date = parseTime(new Date(), "{y}/{m}/{d}")
    timeData.value.time = parseTime(new Date(), "{h}:{i}:{s}")
    timeData.value.week = parseTime(new Date(), "星期{a}")
    if (props.modelValue) getDate()
  }, 900)
}
</script>

<style lang="scss">
.my-drawer {
  width: 100% !important;
  height: 100vh !important;
  z-index: 99999999999999;
  background-image: url("https://xc-goods.oss-cn-shenzhen.aliyuncs.com/20240612/data/Company/%28bg%29%2B0305162095523c88dd347d1b7cc617f632b7efdb7.png");
  .el-drawer__header {
  }
  .el-drawer__body {
    padding: 0;
  }
}

.home-board-screen {
  display: inline-block;
  width: 1920px; //设计稿的宽度
  height: 1080px; //设计稿的高度
  transform-origin: 0 0;
  position: absolute;
  left: 100%;
}

@import "./style.scss";
</style>
